#!/usr/bin/env python
#!coding:utf-8

import  requests
from urllib import  parse
import  json
from threading import Thread
import  numpy as np
import  matplotlib.pyplot as plt

def request(api):
	'''
	对请求方法进行二次封装
	:param api: api是Api模型里面Api的对象
	:return:
	'''
	host=api.host.host
	method=api.http_method
	path=api.path
	url=parse.urljoin(host,path)
	#对请求参数进行处理
	data={}
	if api.data:
		data_list=json.loads(api.data,encoding='utf-8')
		for data_dict in data_list:
			# [{name:"username",value:"password"}]
			data[data_dict['name']]=data_dict['value']
	headers={}
	if api.headers:
		header_list=json.loads(api.headers,encoding='utf-8')
		for header_dict in header_list:
			headers[header_dict['name']]=header_dict['value']
	r=requests.request(method=method,url=url,headers=headers,json=data)
	print('请求方法:',method)
	print('请求地址:',url)
	print('请求头:',headers)
	print('请求参数:',data)
	return r

class apiThread(Thread):
	'''获取被测函数的响应结果信息数据'''
	def __init__(self,func,args=()):
		'''
		:param func: 被测试的函数
		:param args: 被测试的函数的返回值
		'''
		super(apiThread,self).__init__()
		self.func=func
		self.args=args

	def run(self) -> None:
		self.result=self.func(*self.args)

	def getResult(self):
		try:
			return self.result
		except BaseException as e:
			return e.args[0]

def  performance(code,seconds,text,api):
	'''对接口进行并发请求'''
	r=request(api=api)
	print('响应结果信息:',r.text)
	code=r.status_code
	seconds=r.elapsed.total_seconds()
	text=r.text
	return code,seconds,text



def calculationTime(startTime,endTime):
	'''计算两个时间之差，单位是秒'''
	return (endTime-startTime).seconds

def getResult(seconds):
	'''获取服务端的响应时间信息'''
	data={
		'Max':sorted(seconds)[-1],
		'Min':sorted(seconds)[0],
		'Median':np.median(seconds),
		'99%Line':np.percentile(seconds,99),
		'95%Line':np.percentile(seconds,95),
		'90%Line':np.percentile(seconds,90)
	}
	return data

def show(i,j):
	'''
	:param i: 请求总数
	:param j: 请求响应时间列表
	:return:
	'''
	fig,ax=plt.subplots()
	ax.plot(list_count,seconds)
	ax.set(xlabel='number of times', ylabel='Request time-consuming',
	       title='olap continuous request response time (seconds)')
	ax.grid()
	fig.savefig('olap.png')
	plt.show()